package com.auction.controller;

import com.auction.common.core.controller.MyBaseController;
import com.auction.common.utils.DateUtil;
import com.auction.common.utils.ReturnResult;
import com.auction.config.MinioConfig;
import com.auction.utils.MinioUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;

/**
 * Minio控制层
 */
@Log4j2
@RestController
@RequestMapping("/api/minio")
@Api(tags = "上传接口")
public class MinioController extends MyBaseController {

    final Set<String> imgType = new HashSet<>();
    {
        imgType.add("image/jpeg");
        imgType.add("image/png");
        imgType.add("image/gif");
        imgType.add("image/webp");
        imgType.add("image/tiff");
    }

    @Autowired
    private MinioUtils minioUtils;

    @Autowired
    private MinioConfig minioConfig;


    @ApiOperation("图片上传")
    @PostMapping("/uploadImages")
    public ReturnResult<String> uploadImages(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return fail("请上传图片");
        }
        //进行文件检验
        String type = file.getContentType();
        if (!imgType.contains(type)) {
            return fail("文件要求为jpeg、png、gif、webp、tiff格式");
        }
        try {
            //文件名
            String fileName = file.getOriginalFilename();
            //进行64位编码
            String base64 = Base64Utils.encodeToString(file.getBytes());
            //生成新文件名
            String newFileName = System.currentTimeMillis()+"."+StringUtils.substringAfterLast(fileName, ".");
            //文件夹名称
            String year = String.valueOf(DateUtil.getYear());// 获取当前年份
            String month = String.valueOf(DateUtil.getMonth());// 获取当前月份
            String dir = year+"/"+month+"/";
            //类型
            minioUtils.uploadImage(minioConfig.getBucketName(), base64,dir,type, newFileName);
            //获取文件外链
            String url = minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(),dir+newFileName);
            String miniUrl = url.split("\\?")[0];
            return success("上传成功",miniUrl);
        } catch (Exception e) {
            log.error("上传失败", e);

        }
        return fail("上传失败");
    }

    /**
     * 文件上传
     *
     * @param file
     */
    @ApiOperation("上传文件")
    @PostMapping("/upload/file")
    public ReturnResult<String> upload(@RequestParam("file") MultipartFile file) {
        try {
            //文件名
            String fileName = file.getOriginalFilename();
            String newFileName = System.currentTimeMillis() + "." + StringUtils.substringAfterLast(fileName, ".");
            //类型
            String contentType = file.getContentType();
            minioUtils.uploadFile(minioConfig.getBucketName(), file, newFileName, contentType);
            String url = minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(),newFileName);
            return success("上传成功",url);
        } catch (Exception e) {
            log.error("上传失败", e);
            return fail("上传失败");
        }
    }

    /**
     * 删除
     *
     * @param fileName
     */
    @ApiOperation("删除图片")
    @DeleteMapping("/delete")
    public ReturnResult<String> delete(@RequestParam("fileName") String fileName) {
        minioUtils.removeFile(minioConfig.getBucketName(), fileName);
        return deleteResult(1);
    }

    /**
     * 获取文件信息
     *
     * @param fileName
     * @return
     */
    @ApiOperation("获取文件信息")
    @GetMapping("/info")
    public ReturnResult<String> getFileStatusInfo(@RequestParam("fileName") String fileName) {
        return success("文件信息",minioUtils.getFileStatusInfo(minioConfig.getBucketName(), fileName));
    }

    /**
     * 获取文件外链
     *
     * @param fileName
     * @return
     */
    @ApiOperation("获取文件外链")
    @GetMapping("/url")
    public ReturnResult<String> getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
        return success("文件外链",minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), fileName));
    }


    /**
     * 文件下载
     *
     * @param fileName
     * @param response
     */
    @ApiOperation("文件下载")
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        try {
            // 从 MinIO 获取指定的对象（文件）的输入流
            InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
            // 设置响应头，指明这是一个附件下载，并指定下载文件的名称
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 设置响应的内容类型为强制下载
            response.setContentType("application/force-download");
            // 设置响应的字符编码为 UTF-8
            response.setCharacterEncoding("UTF-8");
            // 将输入流中的文件内容复制到响应输出流中
            IOUtils.copy(fileInputStream, response.getOutputStream());
            response.flushBuffer(); // 刷新响应输出流
        } catch (Exception e) {
            log.error("下载失败");
            System.out.println(e);
        }
    }
}
